package tr.com.netgis;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;

import tr.com.netgis.db.NGDbHelper;
import tr.com.netgis.pojo.NGLocation;
import tr.com.netgis.web.SetLocationsRequest;
import tr.com.netgis.web.SetLocationsResponse;
import tr.com.netgis.web.WebServisCaller;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;

public class InternetConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        	Log.d("INTERNET", "Provider changed");        	
        } else if (intent.getAction().matches("android.net.conn.CONNECTIVITY_CHANGE")) {
            ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
            if (cm == null)
                return;
            if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
                Log.d("INTERNET", "Internet Connection Established");
                new ProcessTask(context).execute(new Void[]{});
                
            } else {
            	Log.d("INTERNET", "Internet Connection Lost");
            }        	
        }
    }
    
    private SetLocationsResponse sendUnsentLocationsToServer (){
    	SetLocationsRequest request = null;
    	try {
        	List<NGLocation> locations = mHelper.listUnsentLocations();
        	request = new SetLocationsRequest(locations);
    		request.setServerUrl(SharedPrefs.getInstance().getServerUrl());
            SetLocationsResponse response = WebServisCaller.callWebService(request);    	
            if (!response.hasException()) {
            	int [] ids = new int[locations.size()];
            	for (int i = 0; i < locations.size(); i++) {
					ids[i] = locations.get(i).get_id();
				}
            	mHelper.sendLocation(ids);
            }
            return response;			
		} catch (Exception e) {
			Writer wr = new StringWriter();
			PrintWriter pw = new PrintWriter(wr);
			e.printStackTrace(pw);
			SetLocationsResponse response = new SetLocationsResponse(e, request);
			response.setExceptionString(wr.toString());
            FileLogger.log("INTERNET CONNECTION ESTABLISHED:\n" + wr.toString());
            try {
				wr.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return response;
		} finally {
			mHelper.close();
		}
    }
    
    class ProcessTask extends AsyncTask<Void, Void, String>{
    	private Context context;
    	
		public ProcessTask(Context context) {
			super();
			this.context = context;
		}

		@Override
		protected String doInBackground(Void... params) {
			inititializeDB(context);
            SetLocationsResponse response = sendUnsentLocationsToServer();
            FileLogger.log("INTERNET CONNECTION ESTABLISHED:\n" + response);
            return response.toString();
		}
    	
    };
    
	NGDbHelper mHelper;
	
	private void inititializeDB (Context ctx){
		if (mHelper == null) {
			mHelper = new NGDbHelper(ctx);	
		}
	}
	
	

}